package com.control.back.halo.manage.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.control.back.halo.manage.entity.Function;
import com.control.back.halo.manage.service.IFunctionService;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component
public class BreadcrumbModelDirective implements TemplateDirectiveModel {

    private static final String BREADCRUMB_TEMP_URL = "/decorators/breadcrumb.ftl";

    @Autowired
    private IFunctionService    functionService;

    @Autowired
    private Configuration       configuration;

    @Override
    @SuppressWarnings("rawtypes")
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String uriAddress = request.getRequestURI();
        String host = request.getContextPath();
        String linkAddress = StringUtils.substringAfter(uriAddress, host);
        Function function = functionService.findByLink(linkAddress);

        Map<String, Object> data = new LinkedHashMap<String, Object>();
        data.put("function", function);
        Template template = configuration.getTemplate(BREADCRUMB_TEMP_URL);
        // 模板引擎解释模板
        Writer out = env.getOut();
        template.process(data, out);
        out.flush();
    }
}
